/**
 * @Title: ExampleFile.java
 * @Package com.example.package
 * @Description: Placeholder (briefly describe the purpose of this file)
 * @Author: Evan
 * @Date: 2023-08-18
 * @Version: V1.0
 *
 * Copyright Notice:
 * This project is released in open source and follows the applicable open source license.
 * All rights reserved. (c) 2023 Evan.
 * This project is protected by copyright laws and international copyright treaties.
 * Unauthorized reproduction, sale, copy, modification, merge, publication, distribution,
 * licensing, and/or sales of this software and its copies are prohibited without permission.
 * Please contact the author for authorization.
 * Contact Information:
 * @Email: uyevan@163.com
 */

package com.evan.biznak.vip.Fragment;

import static com.evan.biznak.vip.Config.Config.API_URL;
import static com.evan.biznak.vip.Config.Config.APP_ID;
import static com.evan.biznak.vip.Config.Config.KEEPER;
import static com.evan.biznak.vip.Util.FileUtil.evanVip;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;

import com.evan.biznak.vip.Class.AppData;
import com.evan.biznak.vip.R;
import com.evan.biznak.vip.Util.AES;
import com.evan.biznak.vip.Util.SharePreferencesUtils;
import com.evan.biznak.vip.Util.WindowUtils;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.card.MaterialCardView;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.google.android.material.textview.MaterialTextView;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Base64;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;

import es.dmoral.toasty.Toasty;



public class KoznakFragment extends Fragment {

    /*本Fragment*/
    private View view;
    private Context context;
    private Activity activity;

    /* dia_main_view 控件 */
    private View dia_main_view;
    private TextInputLayout phone_layout, code_layout;
    private TextInputEditText phone, code;
    private MaterialButton get_start, get_vip;
    private MaterialCardView data_card;

    /*token验证*/
    private MaterialTextView user_data;

    /*输出结果*/
    private NestedScrollView out_scroll;
    private MaterialTextView out_text;

    /*Loading*/
    private KProgressHUD kProgressHUD;

    /*单一规则*/
    private boolean getIntegral = true;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_koznak, container, false);
        /*上下文初始化*/
        this.context = requireContext();
        this.activity = requireActivity();
        /*初始化*/
        initView();
        /*Dialog*/
        kProgressHUD = KProgressHUD.create(context).setStyle(KProgressHUD.Style.SPIN_INDETERMINATE).setLabel("Biznak并发请求中").setDetailsLabel(getString(R.string._3)).setCancellable(false).setAnimationSpeed(2).setDimAmount(0.5f);
        return view;
    }

    @SuppressLint("InflateParams")
    private void initView() {
        /*dia_main_view*/
        dia_main_view = getLayoutInflater().inflate(R.layout.dia_main_view, null);
        phone_layout = dia_main_view.findViewById(R.id.phone_layout);
        code_layout = dia_main_view.findViewById(R.id.code_layout);
        phone = dia_main_view.findViewById(R.id.phone);
        code = dia_main_view.findViewById(R.id.code);
        /*本view*/
        user_data = view.findViewById(R.id.user_data);
        get_start = view.findViewById(R.id.get_start);
        get_vip = view.findViewById(R.id.get_vip);
        data_card = view.findViewById(R.id.data_card);
        out_scroll = view.findViewById(R.id.out_scroll);
        out_text = view.findViewById(R.id.out_data);
        out_text.setVisibility(View.GONE);
        out_scroll.setVisibility(View.GONE);
        /*本地账号验证*/
        Log.e("status", String.valueOf(SharePreferencesUtils.checkString(context, "koz_web_token")));
        if (!SharePreferencesUtils.checkString(context, "koz_web_token")) {
            userLogin();
            new MaterialAlertDialogBuilder(context).setIcon(R.drawable.twotone_cruelty_free_24).setNegativeButton(getString(R.string.确认), null).setTitle(R.string.koznak脚本的使用).setMessage(R.string._1_koznak_2_3_5).setCancelable(false).show();
            return;
        }
        userResource();
    }


    /**
     * User login.
     */
    @SuppressLint("InflateParams")
    public void userLogin() {
        /*隐藏code_layout*/
        /*code_layout.setVisibility(View.GONE);*/
        // Dialog
        final AlertDialog mDialog = new MaterialAlertDialogBuilder(context).setIcon(R.drawable.twotone_cruelty_free_24).setPositiveButton("获取验证码", null).setNegativeButton("取消", null).setTitle("Koznak登录验证").setMessage("为了开启会员您需要进行手机号登录，登录完后我们才能为你提供更多的服务。请通过你登录Koznak的是手机号来进行登录。").setView(dia_main_view).setCancelable(false).create();

        mDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                Button positiveButton = mDialog.getButton(AlertDialog.BUTTON_POSITIVE);
                Button negativeButton = mDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
                positiveButton.setOnClickListener(v -> {
                    String phone_d = Objects.requireNonNull(phone.getText()).toString().trim();
                    if (phone_d.isEmpty()) {
                        phone_layout.setError("手机号不能为空");
                        Toasty.error(context, "手机号不能为空", Toasty.LENGTH_SHORT, true).show();
                        return;
                    }
                    /*Layout 改成默认*/
                    phone_layout.setError(null);
                    /*正则 第一个数字1开头 | 第二个数字取3到9的任意 | 后面跟着9个数字*/
                    String regex = "^1[3-9]\\d{9}$";
                    if (!Pattern.matches(regex, phone_d)) {
                        phone_layout.setError("手机号格式有问题请修正");
                        Toasty.error(context, "手机号格式有问题请修正", Toasty.LENGTH_SHORT, true).show();
                        return;
                    }
                    /* 代刷检测 */
                    if (!AppData.getSignName().equals("本人无个性的签名")) {
                        /* 已经进行过刷会员 */
                        if (!AppData.getSignName().equals(phone_d)) {
                            /* 隐藏键盘 */
                            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.hideSoftInputFromWindow(null, 0);
                            mDialog.dismiss();
                            /* 手机号进行了更改*/
                            final AlertDialog dialogs = new MaterialAlertDialogBuilder(context)
                                    .setPositiveButton("解决问题", null)
                                    .setNegativeButton("退出", null)
                                    .setCancelable(false)
                                    .setTitle("系统警告提示")
                                    .setMessage("\t非常抱歉打扰您，我们注意到您的账户似乎存在代刷行为。我们希望提醒您，代刷行为违反了我们的用户协议，并且可能会对平台和其他用户造成负面影响。为了维护公平、稳定的交易环境，我们需要您配合进行核查和解决。\n\t请您点击下方的按钮，按照提示提交相关资料，我们将在收到您的信息后进行审核并尽快给出回复。请注意，如果我们再次发现您的账户存在代刷等违规行为，我们将会采取封号等措施。感谢您的理解和配合，祝您使用愉快！")
                                    .create();
                            dialogs.setOnShowListener(dialogs_s -> {
                                Button N_button = dialogs.getButton(DialogInterface.BUTTON_NEGATIVE);
                                Button P_button = dialogs.getButton(DialogInterface.BUTTON_POSITIVE);
                                /*接受*/
                                P_button.setOnClickListener(vp -> {
                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("mqqwpa://im/chat?chat_type=wpa&uin=" + "3487297072" + "&version=1")));
                                });
                                /*拒绝*/
                                N_button.setOnClickListener(vn -> {
                                    dialogs.dismiss();
                                    activity.finish();
                                });
                            });
                            dialogs.show();
                            return;
                        }
                    }
                    /*Layout 改成默认*/
                    phone_layout.setError(null);
                    HttpParams params = new HttpParams();
                    params.put("nns_user_agent", "nn_phone/android_phone/1.0.0");
                    params.put("nns_tag", "29");
                    params.put("nns_version", "8.8.1.android_Koznak_release");
                    params.put("nns_user_telephone", phone_d);
                    params.put("nns_output_type", "json");
                    params.put("nns_func", "scaaa_get_verify_code_by_mobile");
                    if (WindowUtils.checkNetworkStatus(context)) {
                        EasyHttp.get("http://aaa.koznak.tv:88/nn_cms/nn_cms_view/xjcbc/n217_a.php").params(params).execute(new SimpleCallBack<String>() {
                            @Override
                            public void onError(ApiException e) {
                                Toasty.error(context, Objects.requireNonNull(e.getMessage()), Toasty.LENGTH_SHORT, true).show();
                            }

                            @Override
                            public void onSuccess(String data) {
                                try {
                                    JSONObject jsonObject = new JSONObject(data);
                                    JSONObject json_result = jsonObject.getJSONObject("result");
                                    if (json_result.getInt("state") != 300000) {
                                        phone_layout.setError("获取验证码失败，请重试");
                                        Toasty.error(context, json_result.getString("reason"), Toasty.LENGTH_SHORT, true).show();
                                        return;
                                    }
                                    /*Layout 改成默认*/
                                    phone_layout.setError(null);
                                    Toasty.success(context, json_result.getString("reason"), Toasty.LENGTH_SHORT, true).show();
                                    code.requestFocus(); //设置焦点
                                    Button positiveButton = mDialog.getButton(DialogInterface.BUTTON_POSITIVE);
                                    positiveButton.setText("确认并提交");
                                    positiveButton.setOnClickListener(v -> {
                                        String code_d = Objects.requireNonNull(code.getText()).toString().trim();
                                        /*Empty验证*/
                                        if (code_d.isEmpty()) {
                                            code_layout.setError("验证码不能为空");
                                            Toasty.error(context, "验证码不能为空", Toasty.LENGTH_SHORT, true).show();
                                            return;
                                        }
                                        /*Layout 改成默认*/
                                        code_layout.setError(null);
                                        /*正则六位验证码*/
                                        String regex = "[0-9]\\d{5}$";
                                        if (!Pattern.matches(regex, code_d)) {
                                            code_layout.setError("验证码不规范，请重新输入");
                                            Toasty.error(context, "验证码不规范", Toasty.LENGTH_SHORT, true).show();
                                            return;
                                        }
                                        /*Layout 改成默认*/
                                        code_layout.setError(null);
                                        /*参数封装*/
                                        HttpParams params = new HttpParams();
                                        params.put("nns_ticket", "");
                                        params.put("nns_login_type", "aaa");
                                        params.put("nns_user_password", "");
                                        params.put("nns_user_id", phone_d);
                                        params.put("nns_code", code_d);
                                        params.put("nns_invitation_code", "");
                                        params.put("nns_user_agent", "nn_phone/android_phone/1.0.0");
                                        params.put("group", "koznakAndroid");
                                        params.put("nns_version", "8.8.1.android_Koznak_release");
                                        params.put("nns_tag", "29");
                                        params.put("Codec", "10051002");
                                        params.put("nns_output_type", "json");
                                        params.put("nns_func", "scaaa_user_login");
                                        if (WindowUtils.checkNetworkStatus(context)) {
                                            EasyHttp.get("http://aaa.koznak.tv:88/nn_cms/nn_cms_view/xjcbc/n215_a.php").params(params).execute(new SimpleCallBack<String>() {
                                                @Override
                                                public void onError(ApiException e) {
                                                    Toasty.error(context, Objects.requireNonNull(e.getMessage()), Toasty.LENGTH_SHORT, true).show();
                                                }

                                                @RequiresApi(api = Build.VERSION_CODES.O)
                                                @Override
                                                public void onSuccess(String s) {
                                                    byte[] decode = Base64.getDecoder().decode(s);
                                                    String decode_data = new String(decode);
                                                    String data = decode_data.substring(decode_data.indexOf("{\"result\""));
                                                    Log.e("data", data);
                                                    try {
                                                        JSONObject jsonObject = new JSONObject(data);
                                                        JSONObject json_result = jsonObject.getJSONObject("result"); // 状态
                                                        if (json_result.getInt("state") != 300000) {
                                                            code_layout.setError(json_result.getString("reason"));
                                                            Toasty.error(context, "授权失败", Toasty.LENGTH_SHORT, true).show();
                                                            return;
                                                        }
                                                        /* 手机号更新到SIGN */
                                                        HttpParams params = new HttpParams();
                                                        params.put("keeper", evanVip(KEEPER, context));
                                                        params.put("api", evanVip(APP_ID, context));
                                                        params.put("user", getDeviceId());
                                                        params.put("pass", getIccId());
                                                        params.put("newsign", phone_d);
                                                        if (WindowUtils.checkNetworkStatus(context)) {
                                                            EasyHttp.get(evanVip(API_URL, context).concat("user_newsign.php")).params(params).execute(new SimpleCallBack<String>() {
                                                                @Override
                                                                public void onError(ApiException e) {
                                                                    activity.finish();
                                                                }

                                                                @Override
                                                                public void onSuccess(String data) {
                                                                    String s = AES.decrypt(data, context);
                                                                    try {
                                                                        JSONObject jsonObject = new JSONObject(s);
                                                                        if (!jsonObject.getString("code").equals("true")) {
                                                                            Toasty.error(context, "出了点小插曲~", Toasty.LENGTH_SHORT, true).show();
                                                                        }
                                                                    } catch (JSONException e) {
                                                                        throw new RuntimeException(e);
                                                                    } finally {
                                                                        kProgressHUD.dismiss();
                                                                    }
                                                                }
                                                            });
                                                        }
                                                        JSONObject json_auth = jsonObject.getJSONObject("auth"); // token
                                                        JSONObject json_user = jsonObject.getJSONObject("user"); // user 数据
                                                        positiveButton.setText("授权成功");
                                                        Toasty.success(context, "授权成功", Toasty.LENGTH_SHORT, true).show();
                                                        /*存储必要信息*/
                                                        SharePreferencesUtils.saveString(context, "koz_phone", phone_d); //手机号
                                                        SharePreferencesUtils.saveString(context, "koz_web_token", json_auth.getString("web_token")); //token
                                                        SharePreferencesUtils.saveString(context, "koz_user_id", json_user.getString("id")); // id
                                                        SharePreferencesUtils.saveString(context, "koz_user_password", json_user.getString("password")); //pass
                                                        /*第一次运行初始化*/
                                                        getIntegral();
                                                        try {
                                                            Thread.sleep(1000);
                                                        } catch (InterruptedException e) {
                                                            throw new RuntimeException(e);
                                                        }
                                                        mDialog.dismiss();
                                                        /*获取用户信息*/
                                                        userResource();
                                                    } catch (JSONException e) {
                                                        throw new RuntimeException(e);
                                                    }
                                                }
                                            });
                                        }
                                    });
                                } catch (JSONException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        });
                    }
                });
                negativeButton.setOnClickListener(v -> {
                    mDialog.dismiss();
                });
            }
        });
        mDialog.show();
    }

    /*获取设备信息*/
    // 账户
    @SuppressLint("HardwareIds")
    private String getDeviceId() {
        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID).replaceAll("\\D+", ""); //AndroidID
    }

    // 密码
    @SuppressLint("HardwareIds")
    private String getIccId() {
        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID).replaceAll("\\D+", ""); //AndroidIDv
    }

    /*数据加载*/
    private void userResource() {
        Toasty.success(requireActivity(), "执行完成数据已更新", Toasty.LENGTH_SHORT, true).show();
        data_card.setVisibility(View.VISIBLE);
        get_start.setVisibility(View.VISIBLE);
        get_vip.setVisibility(View.VISIBLE);
        /*参数封装*/
        HttpParams params = new HttpParams();
        params.put("nns_func", "scaaa_get_user_info");
        params.put("nns_output_type", "json");
        params.put("nns_user_id", SharePreferencesUtils.getString(context, "koz_user_id"));
        params.put("nns_webtoken", SharePreferencesUtils.getString(context, "koz_web_token"));
        params.put("nns_version", "8.8.1.android_Koznak_release");
        if (WindowUtils.checkNetworkStatus(context)) {
            EasyHttp.get("http://aaa.koznak.tv:88/nn_cms/nn_cms_view/xjcbc/n217_a.php").params(params).execute(new SimpleCallBack<String>() {
                @Override
                public void onError(ApiException e) {
                    Toasty.error(context, Objects.requireNonNull(e.getMessage()), Toasty.LENGTH_SHORT, true).show();
                }

                @SuppressLint("SetTextI18n")
                @Override
                public void onSuccess(String s) {
                    Log.e("data", s);
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        JSONObject json_result = jsonObject.getJSONObject("result"); // 状态
                        if (json_result.getInt("state") != 300000) {
                            Toasty.error(context, json_result.getString("reason"), Toasty.LENGTH_SHORT, true).show();
                            /*清理Share*/
                            SharePreferencesUtils.clear(context);
                            return;
                        }
                        JSONObject json_user = jsonObject.getJSONObject("user"); // user 数据
                        Toasty.success(context, "授权成功", Toasty.LENGTH_SHORT, true).show();
                        /*更新必要信息*/
                        SharePreferencesUtils.saveString(context, "koz_phone", json_user.getString("telephone")); //手机号
                        SharePreferencesUtils.saveString(context, "koz_user_id", json_user.getString("id")); // id
                        if (json_user.has("password")) {
                            SharePreferencesUtils.saveString(context, "koz_user_password", json_user.getString("password")); //pass
                        }
                        try {
                            /*积分*/
                            // JSONObject user_integral = json_user.getJSONObject("user_integral");
                            Object userIntegral = json_user.get("user_integral");
                            if (userIntegral instanceof JSONArray) {
                                Log.e("data", "JSONArray");
                                // user_integral 是一个 JSON 数组，表示该用户没有积分记录
                                JSONArray userIntegralArray = (JSONArray) userIntegral;
                                /*获取积分*/
                                if (getIntegral) {
                                    getIntegral();
                                }
                                // 处理 user_integral 数组
                            } else if (userIntegral instanceof JSONObject) {
                                Log.e("data", "JSONObject");
                                // user_integral 是一个 JSON 对象，表示该用户有积分记录，但当前积分数为 0
                                JSONObject user_integral = (JSONObject) userIntegral;
                                // 001
                                if (user_integral.has("001")) {
                                    JSONObject integral_001 = user_integral.getJSONObject("001");
                                    user_data.setText(getUserText().concat(integral_001.getString("nns_type") + "积分：" + integral_001.getString("nns_integral"))); // 001积分
                                }
                            }
                            // farm_002
                                /*if (user_integral.has("farm_002")) {
                                    JSONObject integral_002 = user_integral.getJSONObject("farm_002");
                                    user_data.setText(getUserText().concat(integral_002.getString("nns_type") + "积分：" + integral_002.getString("nns_integral"))); // 002积分
                                }*/
                            // farm_001
                                /*if (user_integral.has("farm_001")) {
                                    JSONObject integral_002 = user_integral.getJSONObject("farm_001");
                                    user_data.setText(getUserText().concat(integral_002.getString("nns_type") + "积分：" + integral_002.getString("nns_integral"))); // 002积分
                                }*/
                            // jyl_001
                                /*if (user_integral.has("jyl_001")) {
                                    JSONObject integral_002 = user_integral.getJSONObject("jyl_001");
                                    user_data.setText(getUserText().concat(integral_002.getString("nns_type") + "积分：" + integral_002.getString("nns_integral"))); // 002积分
                                }*/
                            /*会员*/
                            JSONArray user_vip = json_user.getJSONArray("user_vip_list");
                            if (user_vip.length() != 0) {
                                JSONObject json_user_vip = user_vip.getJSONObject(0); // 会员信息
                                user_data.setText(getUserText().concat("会员等级：" + json_user_vip.getString("vip_level_name")));
                                user_data.setText(getUserText().concat("会员时间：" + json_user_vip.getString("end_time")));
                            }
                        } catch (JSONException e) {
                            user_data.setText("获取用户数据失败");
                            throw new RuntimeException(e);
                        }
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }

        get_start.setOnClickListener(v -> {
            kProgressHUD.show();
            getStart();
        });
        /*领取会员*/
        get_vip.setOnClickListener(v -> {
            kProgressHUD.show();
            getVip();
        });
    }

    /*线程池*/
    private void getStarts() {
        // 创建一个新的 HttpParams 对象
        HttpParams params = new HttpParams();
        // 添加参数到 HttpParams 对象中
        params.put("nns_func", "scaaa_get_integral_task");
        params.put("nns_output_type", "json");
        params.put("nns_user_id", SharePreferencesUtils.getString(context, "koz_user_id"));
        params.put("nns_webtoken", SharePreferencesUtils.getString(context, "koz_web_token"));
        params.put("nns_version", "8.8.1.android_Koznak_release");
        params.put("nns_page_size", "999");
        if (WindowUtils.checkNetworkStatus(context)) {
            /*发送请求*/
            EasyHttp.get("http://epg.koznak.tv/nn_cms/nn_cms_view/std_new/n224_a.php").params(params).execute(new SimpleCallBack<String>() {
                @Override
                public void onError(ApiException e) {
                    Toasty.error(context, Objects.requireNonNull(e.getMessage()), Toasty.LENGTH_SHORT, true).show();
                }

                @Override
                public void onSuccess(String string) {
                    try {
                        JSONObject jsonObject = new JSONObject(string);
                        JSONObject json_result = jsonObject.getJSONObject("result"); // 状态
                        if (json_result.getInt("state") != 300000) {
                            Toasty.error(context, json_result.getString("reason"), Toasty.LENGTH_SHORT, true).show();
                            return;
                        }
                        JSONArray json_integral = jsonObject.getJSONArray("integral_task"); // 积分数据
                        Toasty.success(context, "开启执行命令", Toasty.LENGTH_SHORT, true).show();
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                out_text.setVisibility(View.VISIBLE);
                                out_scroll.setVisibility(View.VISIBLE);
                            }
                        });
                        /*数组长度*/
                        Log.e("koznak积分表length", String.valueOf(json_integral.length()));
                        setOutData("执行命令开始");
                        /*数组循环解析*/

                        // 创建一个线程池，线程数为10个
                        ExecutorService executorService = Executors.newFixedThreadPool(10);

                        for (int i = 0; i < json_integral.length(); i++) {
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                            int finalI = i;
                            executorService.execute(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        JSONObject integral_object = json_integral.getJSONObject(finalI);
                                        /*参数装库*/
                                        HttpParams params = new HttpParams();
                                        params.put("nns_func", "scaaa_do_integral_task");
                                        params.put("nns_output_type", "json");
                                        params.put("nns_task_id", integral_object.getString("nns_id"));
                                        params.put("nns_user_id", SharePreferencesUtils.getString(context, "koz_user_id"));
                                        params.put("nns_webtoken", SharePreferencesUtils.getString(context, "koz_web_token"));
                                        params.put("nns_version", "8.8.1.android_Koznak_release");
                                        if (integral_object.has("nns_integral_type_id")) {
                                            // continue; // 跳过当前循环迭代
                                            params.put("nns_integral_type_id", integral_object.getString("nns_integral_type_id"));
                                        }
                                        /*自用参数*/
                                        params.put("nns_task_name", integral_object.getString("nns_task_name")); //积分名称
                                        params.put("nns_task_end_time", integral_object.getString("nns_task_end_time")); //结束事件
                                        params.put("nns_order", integral_object.getString("nns_order")); //积分数量

                                        JSONObject task_execute = integral_object.getJSONObject("task_rule");
                                        int nns_task_execute_times = Integer.parseInt(task_execute.getString("nns_task_execute_times"));
                                        Log.e("koznak" + finalI + "个积分表length", String.valueOf(nns_task_execute_times));
                                        /*次数验证*/
                                        int FNUM;
                                        if (nns_task_execute_times == 1) {
                                            FNUM = 1;
                                        } else if (nns_task_execute_times > 1 && nns_task_execute_times <= 100) {
                                            FNUM = 50;
                                        } else if (nns_task_execute_times > 100 && nns_task_execute_times <= 500) {
                                            FNUM = 100;
                                        } else if (nns_task_execute_times > 500 && nns_task_execute_times <= 1000) {
                                            FNUM = 200;
                                        } else {
                                            FNUM = 500;
                                        }

                                        /*循环执行*/
                                        for (int j = 0; j < FNUM; j++) {
                                            Thread.sleep(500);
                                            int finalJ = j;
                                            if (WindowUtils.checkNetworkStatus(context)) {
                                                EasyHttp.get("http://epg.koznak.tv/nn_cms/nn_cms_view/std_new/n224_a.php").params(params).execute(new SimpleCallBack<String>() {
                                                    @Override
                                                    public void onError(ApiException e) {
                                                        Log.e("koznak_error", e.getMessage());
                                                    }

                                                    @Override
                                                    public void onSuccess(String s) {
                                                        try {
                                                            JSONObject jsonObject = new JSONObject(s);
                                                            JSONObject json_result = jsonObject.getJSONObject("result"); // 状态
                                                            if (json_result.getInt("state") != 300000) {
                                                                setOutData("积分" + integral_object.getString("nns_task_name") + "第" + (finalJ + 1) + "次执行失败：原因：" + json_result.getString("reason"));
                                                                return;
                                                            }
                                                            setOutData("积分" + integral_object.getString("nns_task_name") + "第" + (finalJ + 1) + "次执行成功，获得" + integral_object.getString("nns_order") + "积分");
                                                        } catch (JSONException e) {
                                                            e.printStackTrace();
                                                        }
                                                    }
                                                });
                                            }
                                        }
                                    } catch (JSONException | InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        }
                        executorService.shutdown();
                        while (!executorService.isTerminated()) {
                            Thread.sleep(1000);
                        }
                        Toasty.success(context, "所有积分任务执行完毕！", Toasty.LENGTH_SHORT, true).show();
                    } catch (JSONException | InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    /*命令执行*/
    private void getStart() {
        // 创建一个新的 HttpParams 对象
        HttpParams params = new HttpParams();
        // 添加参数到 HttpParams 对象中
        params.put("nns_func", "scaaa_get_integral_task");
        params.put("nns_output_type", "json");
        params.put("nns_user_id", SharePreferencesUtils.getString(context, "koz_user_id"));
        params.put("nns_webtoken", SharePreferencesUtils.getString(context, "koz_web_token"));
        params.put("nns_version", "8.8.1.android_Koznak_release");
        params.put("nns_page_size", "999");
        if (WindowUtils.checkNetworkStatus(context)) {
            /*发送请求*/
            EasyHttp.get("http://epg.koznak.tv/nn_cms/nn_cms_view/std_new/n224_a.php").params(params).execute(new SimpleCallBack<String>() {
                @Override
                public void onError(ApiException e) {
                    Toasty.error(context, Objects.requireNonNull(e.getMessage()), Toasty.LENGTH_SHORT, true).show();
                }

                @Override
                public void onSuccess(String string) {
                    try {
                        JSONObject jsonObject = new JSONObject(string);
                        JSONObject json_result = jsonObject.getJSONObject("result"); // 状态
                        if (json_result.getInt("state") != 300000) {
                            Toasty.error(context, json_result.getString("reason"), Toasty.LENGTH_SHORT, true).show();
                            return;
                        }
                        JSONArray json_integral = jsonObject.getJSONArray("integral_task"); // 积分数据
                        Toasty.success(context, "开启执行命令", Toasty.LENGTH_SHORT, true).show();
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                out_text.setVisibility(View.VISIBLE);
                                out_scroll.setVisibility(View.VISIBLE);
                            }
                        });
                        /*数组长度*/
                        Log.e("koznak积分表length", String.valueOf(json_integral.length()));
                        setOutData("执行命令开始");
                        /*数组循环解析*/
                        for (int i = 0; i < json_integral.length(); i++) {
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                            int finalI = i;
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        JSONObject integral_object = json_integral.getJSONObject(finalI);
                                        /*参数装库*/
                                        HttpParams params = new HttpParams();
                                        params.put("nns_func", "scaaa_do_integral_task");
                                        params.put("nns_output_type", "json");
                                        params.put("nns_task_id", integral_object.getString("nns_id"));
                                        params.put("nns_user_id", SharePreferencesUtils.getString(context, "koz_user_id"));
                                        params.put("nns_webtoken", SharePreferencesUtils.getString(context, "koz_web_token"));
                                        params.put("nns_version", "8.8.1.android_Koznak_release");
                                        if (integral_object.has("nns_integral_type_id")) {
                                            // continue; // 跳过当前循环迭代
                                            params.put("nns_integral_type_id", integral_object.getString("nns_integral_type_id"));
                                        }
                                        /*自用参数*/
                                        params.put("nns_task_name", integral_object.getString("nns_task_name")); //积分名称
                                        params.put("nns_task_end_time", integral_object.getString("nns_task_end_time")); //结束事件
                                        params.put("nns_order", integral_object.getString("nns_order")); //积分数量

                                        JSONObject task_execute = integral_object.getJSONObject("task_rule");
                                        int nns_task_execute_times = Integer.parseInt(task_execute.getString("nns_task_execute_times"));
                                        Log.e("koznak" + finalI + "个积分表length", String.valueOf(nns_task_execute_times));
                                        /*次数验证*/
                                        int FNUM;
                                        if (nns_task_execute_times == 1) {
                                            FNUM = 1;
                                        } else if (nns_task_execute_times > 1 && nns_task_execute_times <= 100) {
                                            FNUM = 50;
                                        } else if (nns_task_execute_times > 100 && nns_task_execute_times <= 500) {
                                            FNUM = 100;
                                        } else if (nns_task_execute_times > 500 && nns_task_execute_times <= 1000) {
                                            FNUM = 500;
                                        } else {
                                            FNUM = 1;
                                        }
                                        Log.e("koznak" + finalI + "个积分表FNUM", String.valueOf(FNUM));
                                        for (int j = 0; j < FNUM; j++) {
                                            try {
                                                Thread.sleep(500);
                                            } catch (InterruptedException e) {
                                                throw new RuntimeException(e);
                                            }
                                            int finalJ = j;
                                            if (WindowUtils.checkNetworkStatus(context)) {
                                                EasyHttp.get("http://aaa.koznak.tv:88/nn_cms/nn_cms_view/xjcbc/n224_a.php").params(params).execute(new SimpleCallBack<String>() {
                                                    @Override
                                                    public void onError(ApiException e) {
                                                        /*失败内统计*/
                                                        setOutData("第" + finalI + "条指令执第" + finalJ + "次行失败");
                                                    }

                                                    @Override
                                                    public void onSuccess(String s) {
                                                        try {
                                                            JSONObject jsonObject = new JSONObject(s);
                                                            JSONObject json_result = jsonObject.getJSONObject("result"); // 状态
                                                            if (json_result.getInt("state") != 300000) {
                                                                setOutData("第" + finalI + "条指令第" + finalJ + "次执行失败");
                                                                return;
                                                            }
                                                            setOutData("第" + finalI + "条指令第" + finalJ + "次执行成功：" + integral_object.getString("nns_task_name") + " || 获取的积分：" + integral_object.getString("nns_order"));
                                                        } catch (JSONException e) {
                                                            throw new RuntimeException(e);
                                                        }
                                                    }
                                                });
                                            }
                                        }
                                        /*new GetThread(params);*/
                                    } catch (JSONException e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                            }).start();
                        }
                        kProgressHUD.dismiss();
                        /*显示按钮*/
                        get_vip.setVisibility(View.VISIBLE);
                        /*所有线程结束并执行userResource*/
                        user_data.setText("");
                        userResource();
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }

    /*设置终端内容*/
    private void setOutData(final String data) {
        // 创建一个新的线程并运行任务
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 将结果发送到 UI 线程中更新终端输出
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        out_text.append(data + "\n");
                        out_scroll.fullScroll(NestedScrollView.FOCUS_DOWN);
                    }
                });
            }
        }).start();
    }

    /*转成会员*/
    private void getVip() {
        // 创建一个新的 HttpParams 对象
        HttpParams params = new HttpParams();
        // 添加参数到 HttpParams 对象中
        params.put("nns_func", "scaaa_get_exchange_list");
        params.put("nns_output_type", "json");
        params.put("nns_user_id", SharePreferencesUtils.getString(context, "koz_user_id"));
        params.put("nns_webtoken", SharePreferencesUtils.getString(context, "koz_web_token"));
        params.put("nns_integral_type_id", "001");
        params.put("nns_version", "8.8.1.android_Koznak_release");
        params.put("nns_page_size", "999");
        if (WindowUtils.checkNetworkStatus(context)) {
            /*发送请求*/
            EasyHttp.get("http://epg.koznak.tv/nn_cms/nn_cms_view/std_new/n224_a.php").params(params).execute(new SimpleCallBack<String>() {
                @Override
                public void onError(ApiException e) {
                    Toasty.error(context, Objects.requireNonNull(e.getMessage()), Toasty.LENGTH_SHORT, true).show();
                }

                @Override
                public void onSuccess(String string) {
                    try {
                        JSONObject jsonObject = new JSONObject(string);
                        JSONObject json_result = jsonObject.getJSONObject("result"); // 状态
                        if (json_result.getInt("state") != 300000) {
                            Toasty.error(context, json_result.getString("reason"), Toasty.LENGTH_SHORT, true).show();
                            return;
                        }
                        JSONArray json_integral = jsonObject.getJSONArray("integral_task"); // 积分数据
                        Log.e("koznak会员表length", String.valueOf(json_integral.length()));
                        Toasty.success(context, "领取会员命令开启执行", Toasty.LENGTH_SHORT, true).show();
                        /*数组循环解析*/
                        for (int i = 0; i < json_integral.length(); i++) {
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                            int finalI = i;
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        // setOutData("第" + i + "条指令并发中");
                                        JSONObject integral_object = json_integral.getJSONObject(finalI);
                                        /*参数装库*/
                                        HttpParams params = new HttpParams();
                                        params.put("nns_func", "scaaa_exchange_goods");
                                        params.put("nns_user_id", SharePreferencesUtils.getString(context, "koz_user_id"));
                                        params.put("nns_webtoken", SharePreferencesUtils.getString(context, "koz_web_token"));
                                        params.put("nns_integral_type_id", "001");
                                        params.put("nns_version", "8.8.1.android_Koznak_release");
                                        params.put("nns_exchange_id", integral_object.getString("nns_id"));
                                        /*自用参数*/
                                        params.put("nns_integral_type_id", integral_object.getString("nns_integral_type_id")); //活动类型
                                        params.put("nns_exchange_name", integral_object.getString("nns_exchange_name")); //会员名称
                                        params.put("nns_exchange_end_time", integral_object.getString("nns_exchange_end_time")); //结束时间
                                        params.put("nns_free_time", integral_object.getString("nns_free_time")); //会员天数

                                        /*并发处理*/
                                        /*获取重发数量*/
                                        JSONObject task_execute = integral_object.getJSONObject("rule_info");
                                        int nns_exchange_execute_times = Integer.parseInt(task_execute.getString("nns_exchange_execute_times"));
                                        Log.e("koznak" + finalI + "个会员表length", String.valueOf(nns_exchange_execute_times));
                                        /*次数验证*/
                                        int FNUM;
                                        if (nns_exchange_execute_times == 1) {
                                            FNUM = 1;
                                        } else if (nns_exchange_execute_times > 1 && nns_exchange_execute_times <= 100) {
                                            FNUM = 50;
                                        } else if (nns_exchange_execute_times > 100 && nns_exchange_execute_times <= 500) {
                                            FNUM = 100;
                                        } else if (nns_exchange_execute_times > 500 && nns_exchange_execute_times <= 1000) {
                                            FNUM = 500;
                                        } else {
                                            FNUM = 1;
                                        }
                                        Log.e("koznak" + finalI + "个会员表FNUM", String.valueOf(FNUM));
                                        for (int j = 0; j < FNUM; j++) {
                                            try {
                                                Thread.sleep(500);
                                            } catch (InterruptedException e) {
                                                throw new RuntimeException(e);
                                            }
                                            int finalJ = j;
                                            if (WindowUtils.checkNetworkStatus(context)) {
                                                EasyHttp.get("http://aaa.koznak.tv:88/nn_cms/nn_cms_view/xjcbc/n224_a.php").params(params).execute(new SimpleCallBack<String>() {
                                                    @Override
                                                    public void onError(ApiException e) {
                                                        /*失败内统计*/
                                                        setOutData("第" + finalI + "条指令第" + finalJ + "次执行失败");
                                                    }

                                                    @Override
                                                    public void onSuccess(String s) {
                                                        Log.e("data", s);
                                                        try {
                                                            JSONObject jsonObject = new JSONObject(s);
                                                            JSONObject json_result = jsonObject.getJSONObject("result"); // 状态
                                                            if (json_result.getInt("state") != 300000) {
                                                                setOutData("第" + finalI + "条指令第" + finalJ + "次执行失败");
                                                                return;
                                                            }
                                                            setOutData("第" + finalI + "条指令第" + finalJ + "次执行成功：" + integral_object.getString("nns_exchange_name") + " || 获取的会员：" + integral_object.getString("nns_free_time") + "天");
                                                        } catch (JSONException e) {
                                                            throw new RuntimeException(e);
                                                        }
                                                    }
                                                });
                                            }
                                        }
                                    } catch (JSONException e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                            }).start();
                        }
                        kProgressHUD.dismiss();
                        /*所有线程结束并执行userResource*/
                        user_data.setText("");
                        userResource();
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }

    /*获取文本已有是数据*/
    private String getUserText() {
        String str = user_data.getText().toString().trim();
        return str.equals("") ? str : str.concat("\n");
    }


    /*为了数据完整性先领一次积分*/
    private void getIntegral() {
        /*参数装库*/
        HttpParams params = new HttpParams();
        params.put("nns_func", "scaaa_do_integral_task");
        params.put("nns_output_type", "json");
        params.put("nns_task_id", "rzjhhy_1");
        params.put("nns_user_id", SharePreferencesUtils.getString(context, "koz_user_id"));
        params.put("nns_webtoken", SharePreferencesUtils.getString(context, "koz_web_token"));
        params.put("nns_version", "8.8.1.android_Koznak_release");
        params.put("nns_integral_type_id", "001");
        if (WindowUtils.checkNetworkStatus(context)) {
            EasyHttp.get("http://aaa.koznak.tv:88/nn_cms/nn_cms_view/xjcbc/n224_a.php").params(params).execute(new SimpleCallBack<String>() {
                @Override
                public void onError(ApiException e) {
                    /*失败内统计*/
                    setOutData("进程异常，请重新打开应用");
                }

                @Override
                public void onSuccess(String s) {
                    Log.e("getIntegral", s);
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        JSONObject json_result = jsonObject.getJSONObject("result"); // 状态
                        if (json_result.getInt("state") != 300000) {
                            setOutData("进程异常，请重新打开应用");
                            return;
                        }
                        setOutData("初始化成功");
                        getIntegral = false;
                        /*初始化用户数据*/
                        userResource();
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }
}